﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Diagnostics;
using System.IO;

namespace Common.Utility
{
    public static class DebugMode
    {
        public static string GetDebugMode(string assemblyFile)
        {
            Assembly assembly = Assembly.LoadFrom(assemblyFile);
            DebuggableAttribute attr = assembly.GetCustomAttribute<DebuggableAttribute>();
            assembly.GetCustomAttributes(typeof(DebuggableAttribute),false);
            if (attr == null) return "null";
            return attr.IsJITTrackingEnabled ? "Debug" : "Release";
        }
        //public static T GetCustomAttribute<T>(this ICustomAttributeProvider provider) where T : Attribute
        //{
        //    object[] attributes = provider.GetCustomAttributes(typeof(T), false);
        //    return (attributes.Length > 0) ? (attributes[0] as T) : default(T);
        //}

        /// <summary>
        /// 判断指定文件是否Debug版本
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns>是Debug版本返回true，否则返回false</returns>
        public static bool IsDebug(string filePath)
        {
            bool isDebug = false;
            String szName = filePath;
            using (FileStream fs = new FileStream(szName, FileMode.Open, FileAccess.Read))
            {
                using (BinaryReader br = new BinaryReader(fs))
                {
                    fs.Seek(0x3c, SeekOrigin.Begin); // pe heaher offset 
                    int i = br.ReadInt32();

                    fs.Seek(i + 0x18, SeekOrigin.Begin); // magic number offset 
                    int iMagicNumber = br.ReadInt16();
                    if (iMagicNumber == 0x010b)
                    {
                        // pe32 
                        fs.Seek(i + 0xa8, SeekOrigin.Begin);// debug data directories info offset 
                    }
                    else if (iMagicNumber == 0x020b)
                    {
                        // pe32+ 
                        fs.Seek(i + 0xb8, SeekOrigin.Begin);// debug data directories info offset 
                    }

                    else
                    {
                        throw new SystemException("impossible! nnd, it is not a pe file! fk u");
                    }

                    isDebug = br.ReadInt32() != 0;
                }                
            }


            return isDebug;
        }
    }

}
